### Let's apply the ptw - stw on a sample that is in dire need of warping with local flexibility

## Load LC_Temperature data:
data(LC_Temperature)
time <- Temper[1,]

## Select interesting part of data:
Temper <- Temper[,which(time > 10 & time < 60)]
time <-  time[which(time > 10 & time < 60)]

## Remove baseline:
Temper <- baseline.corr(Temper[2:6,])

## Scale samples:
Temper.sc <- t(apply(Temper, 1, function(x) {x/mean(x)}))

## First, we apply ptw, using a third degree warping function and a large triangle width for the WCC criterion:
ref <- Temper.sc[1,]
samp <- Temper.sc[2,]
ptw.res <- ptw(ref, samp, trwdth = 100, init.coef = c(0,1,0,0))

## Let's look at the results:
x11()
plot(ptw.res, what="signal") # "signal" is the default

## And the warping function:
x11()
plot(ptw.res, what="function")

readline("Hit <Return> to proceed:")

## Now let's see if we can optimize this a bit further with stw:
# Note that warping is applied starting from the original reference and sample.
stw.ptw.res <- stw(ptw.res, bspl = 250) 

## Again, let's look at the results:
x11()
plot(stw.ptw.res, what="signal")
x11()
plot(stw.ptw.res, what="function")

## If necessary, the warping function can be applied to e.g. the unscaled data, using try=TRUE:
Final.result <- ptw(Temper[1,], Temper[2,], init.coef = ptw.res$warp.coef, try = TRUE)
Final.result <- stw(Final.result, init.coef = stw.ptw.res$warp.coef, try=TRUE)  
# This generates a warning, since we did not specify the correct number of B-spline basis functions (bspl=250).

x11()
plot(Final.result, what="signal")
x11()
plot(Final.result, what="function")

readline("Hit <Return> to close all graphics windows and end this demo.")
graphics.off()
